package javaScripts;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;

/**
 * Created by lomo on 2017/7.
 */


public class traversalFileMd5 {

    private static ArrayList<String> fileList = new ArrayList<>(); //保存目录
    private static ArrayList<String> pathList = new ArrayList<>(); //保存所有文件的绝对路径


    /**
     *
     * 获取指定文件夹下所有文件目录
     * @param filePath
     * @return ArrayList
     *
     */
    public static ArrayList<String> getFiles(String filePath) {

        File root = new File(filePath);
        File[] files = root.listFiles();

        for(File file:files) {
            if(file.isDirectory()) {
                //System.out.println("检测到子文件夹且该文件夹路径为：" + file.getAbsolutePath());
                getFiles(file.getAbsolutePath());
                fileList.add(file.getAbsolutePath());

            }else {

                //System.out.println("Path: " + filePath + " 下的文件：" + file.getAbsolutePath());
                if(!file.getAbsolutePath().toString().endsWith(".DS_Store"))
                {
                    pathList.add(file.getAbsolutePath());
                }

            }
        }

        return pathList;
    }

    /**
     * 按照字典升序排序
     * @param pathList
     */
    protected static void sortPathList(ArrayList<String> pathList) {
        Collections.sort(pathList);

        System.out.println("\r\n\r\n--------------------------- 所有文件字典序排列后：-------------------------- \r\n");
        for(String str:pathList)
        {
            System.out.println(str);
        }
        System.out.println("\r\n总共 " + pathList.size() + "个文件！！");

    }


    /**
     * 获取所有文件的MD5 并存储至ArrayList
     * @param filePath
     * @return ArrayList
     * @throws FileNotFoundException
     */
    protected static ArrayList<String> getFileMD5List(String filePath) throws Exception{

        ArrayList<String> md5List = new ArrayList<>(); // 保存所有文件的md5

        ArrayList<String> filePathList = getFiles(filePath);
        sortPathList(filePathList);

        for(String s:filePathList) {

            //md5List.add(MD5Utils.calculateFileMD5(s)); //有bug，md5开头为0时有问题
            md5List.add(MD5Utils.getFileMD5(s));
        }

        System.out.println("\r\n -------------------- 字典序后每个文件MD5值：------------------------- \r\n");
        for(String s:md5List) {
            System.out.println(s);
        }
        return md5List;
    }

    /**
     * 将所有MD5合并重新计算
     * @param filePath
     * @return
     * @throws FileNotFoundException
     */
    protected static String getPackagesMD5(String filePath) throws Exception{

        ArrayList<String> fileMD5List = getFileMD5List(filePath);
        StringBuffer newMD5String = new StringBuffer();

        for(String str:fileMD5List) {
            newMD5String.append(str);
        }

        return MD5Utils.getStringMD5(newMD5String.toString());
    }




}
